package com.qiniu.githubdata.utils;

import org.jsoup.nodes.Document;
import java.io.IOException;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.*;

public class IpPool {
    private static final int MAX_POOL_SIZE = 10;
    private static final int VALIDATION_TIMEOUT_SECONDS = 5;
    private static final Queue<ProxyInfo> availableProxies = new ConcurrentLinkedQueue<>();
    private static final Set<ProxyInfo> inUseProxies = ConcurrentHashMap.newKeySet();
    private static final BlockingQueue<ProxyInfo> validationQueue = new LinkedBlockingQueue<>();

    private static final String TEST_URL = "https://github.com";

    static {
        startValidationThread();
    }

    public static ProxyInfo getProxy() {
        // Try to get from available proxies first
        ProxyInfo proxy = availableProxies.poll();

        // If no proxy available and pool not full, fetch new one
        if (proxy == null && getTotalProxies() < MAX_POOL_SIZE) {
            proxy = fetchNewProxy();
        }

        // If proxy found and valid, mark as in use
        while (proxy != null) {
            if(validateProxy(proxy))
            {
                inUseProxies.add(proxy);
                return proxy;
            }else{
                proxy = fetchNewProxy();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        return null;
    }

    public static void releaseProxy(ProxyInfo proxy) {
        if (proxy != null && inUseProxies.remove(proxy)) {
            validationQueue.offer(proxy);
        }
    }

    private static int getTotalProxies() {
        return availableProxies.size() + inUseProxies.size();
    }

    public static ProxyInfo fetchNewProxy() {
        try {
            ProxyInfo res= ProxyUtil.getProxyInfo();
            return res;
        } catch (IOException e) {
            System.err.println("Failed to fetch new proxy: " + e.getMessage());
            return null;
        }
    }

//    private static boolean validateProxy(ProxyInfo proxy) {
//        try {
//            CompletableFuture<Boolean> future = CompletableFuture.supplyAsync(() -> {
//                try {
//                    Document doc = ProxyUtil.fetchContentThroughProxy(TEST_URL, proxy.ip, proxy.port);
//                    return doc != null && doc.title().contains("GitHub");
//                } catch (Exception e) {
//                    // print
//                    System.err.println("Failed to validate proxy: " + e.getMessage());
//                    return false;
//                }
//            });
//
//            return future.get(VALIDATION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
//        } catch (Exception e) {
//            return false;
//        }
//    }
private static boolean validateProxy(ProxyInfo proxy) {
    try {
        // 直接使用同步方式进行网络请求
        Document doc = ProxyUtil.fetchContentThroughProxy(TEST_URL, proxy.ip, proxy.port);
        return doc != null && doc.title().contains("GitHub");
    } catch (Exception e) {
        // 打印错误信息
        System.err.println("Failed to validate proxy: " + e.getMessage());
        return false;
    }
}
    private static void startValidationThread() {
//        Thread validationThread = new Thread(() -> {
//            while (!Thread.currentThread().isInterrupted()) {
//                try {
//                    ProxyInfo proxy = validationQueue.poll(1, TimeUnit.SECONDS);
//                    if (proxy != null) {
//                        if (validateProxy(proxy)) {
//                            availableProxies.offer(proxy);
//                        }
//                    }
//                } catch (InterruptedException e) {
//                    Thread.currentThread().interrupt();
//                }
//            }
//        });
//        validationThread.setDaemon(true);
//        validationThread.start();
    }
}